<template>
  <w-base
    ref="WBase"
    :input="false"
    :souce-url="souceUrl"
    :size="size"/>
</template>

<script>
  import API from '@/api/apis'
  import {upImage} from '@/api/ajax'
  import WBase from './base'

  /**
   * 图片上传组件
   */
  export default {
    name: 'ComGlobalImageUp',
    inject: ['bgImage'],
    components: {
      WBase
    },
    props: {
      /**
       * 试图大小
       */
      size: {
        type: String,
        default: '200px'
      }
    },
    data() {
      return {
        /**
         * 服务器获取的文件数据
         */
        serverFileData: null,
        /**
         * 图片原图
         */
        souceUrl: null
      }
    },
    methods: {
      /**
       * 上传图片
       * @returns {*}
       */
      async upImage() {
        return new Promise((resolve, reject) => {
          this.$refs['WBase'].getImage().then((data) => {
            if (data.type === 'SEL_FILE') {
              upImage (API.server.imageUp, 'file', data.event).then((data) => {
                this.$refs['WBase'].clear()
                this.souceUrl = data.serverPath
                this.serverFileData = data
                resolve(data)
              }).catch((err) => {
                reject(err)
              })
            } else {
              resolve(this.serverFileData)
            }
          }).catch((err) => {
            reject(err)
          })
        })
      },
      /**
       * 清除数据
       */
      clear() {
        this.souceUrl = null
        this.serverFileData = null
        this.$refs['WBase'].clear()
      }
    }
  }
</script>

<style lang="scss" scoped>
</style>

